package com.westa.smallshop.goodssearch;

import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.InflateException;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.westa.smallshop.R;
import com.westa.smallshop.common.BaseActivity;
import com.westa.smallshop.common.BaseListAdapter;
import com.westa.smallshop.common.BaseListFragment;
import com.westa.smallshop.common.BasePresenter;
import com.westa.smallshop.common.GetPresenterInterface;
import com.westa.smallshop.common.RecyclerViewBaseAdapter;
import com.westa.smallshop.data.GoodsItem;
import com.westa.smallshop.goodsdetail.GoodsDetailActivity;
import com.westa.smallshop.util.ListUtils;
import com.westa.smallshop.util.RippleLayout;

import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by cy on 10/11/16.
 */

public class GoodsSearchFragment extends BaseListFragment<GoodsSearchContract.Presenter, GoodsItem>
        implements GoodsSearchContract.View<GoodsItem>, RecyclerViewBaseAdapter.OnItemClickListener, GetPresenterInterface {


    @BindString(R.string.title_search_goods)
    String mTitle;
    @BindView(R.id.tv_no_content)
    TextView mTvNoContent;
    @BindView(R.id.fab_speak)
    FloatingActionButton mFabSpeak;
    @BindView(R.id.ripple_layout)
    RippleLayout mRippleLayout;
    @BindView(R.id.iv_speaking)
    ImageView mIvSpeaking;
    @NonNull
    private GoodsSearchContract.Presenter mPresenter;
    private GoodsSearchAdapter mAdapter;
    private Toolbar mToolbar;
    private EditText mEditText;
    private Vibrator mVibrator;

    private SpeechRecognizer mIat;
    private RecognizerListener mRecognizerListener;

    public static GoodsSearchFragment newInstance() {
        return new GoodsSearchFragment();
    }

    @Override
    public void initView() {
        super.initView();
        getActivity().setTitle(mTitle);
        mToolbar = ((BaseActivity) getActivity()).getToolbar();
        mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);

        if (mToolbar != null) {

            mEditText = (EditText) mToolbar.findViewById(R.id.et_toolbar_search);
            if (mEditText != null) {
                mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            mPresenter.searchGoods(mEditText.getText().toString());

                            return true;
                        }
                        return false;
                    }
                });
            } else {
                throw new InflateException("Search EditText not found");
            }
        } else {
            throw new InflateException("ToolBar not found");
        }
        setRefreshing(false);
        //1.创建SpeechRecognizer对象，第二个参数：本地听写时传InitListener
        mIat = SpeechRecognizer.createRecognizer(getContext(), null);
        //2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
        //3.开始听写   mIat.startListening(mRecoListener);
        // 听写监听器
        mRecognizerListener = new RecognizerListener() {
//            //听写结果回调接口(返回Json格式结果，用户可参见附录12.1)；
//            // 一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
//            // 关于解析Json的代码可参见MscDemo中JsonParser类；
//            // isLast等于true时会话结束。
//            public void onResult(RecognizerResult results, boolean isLast) {
//                Timber.e("Result:", results.getResultString());
//            }

            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {
                if (mVibrator != null) {
                    mVibrator.vibrate(100);
                }
                if (mRippleLayout.isRippleAnimationRunning()) {
                    mRippleLayout.stopRippleAnimation();
                }
                mIvSpeaking.setVisibility(View.VISIBLE);
                mRippleLayout.startRippleAnimation();


            }

            @Override
            public void onEndOfSpeech() {
                if (mVibrator != null) {
                    mVibrator.vibrate(100);
                }
            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                if (mRippleLayout.isRippleAnimationRunning()) {
                    mRippleLayout.stopRippleAnimation();
                    mIvSpeaking.setVisibility(View.GONE);
                }
                Timber.e("-----------------------------------------------------------Result" + recognizerResult.getResultString());
                StringBuilder builder = new StringBuilder();
                SpeechResult speechResult = JSON.parseObject(recognizerResult.getResultString(), SpeechResult.class);
                for (WsBean wsBean : speechResult.getWs()) {
                    for (CwBean cwBean : wsBean.getCw()) {
                        builder.append(cwBean.getW());
                    }
                }
                String result = builder.toString().replaceAll("[\\p{P}]", "");

                if (!TextUtils.isEmpty(result)) {
                    mEditText.setText(result);
                    mEditText.setSelection(result.length());
                    mPresenter.searchGoods(result);
                }
            }

            @Override
            public void onError(SpeechError speechError) {
                Timber.e("-----------------------------------------------------------Error" + speechError.toString());
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        };
    }

    @Override
    public int getCreateViewLayoutRes() {
        return R.layout.fragment_goods_search;
    }

    @NonNull
    @Override
    public BaseListAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new GoodsSearchAdapter(this);
            mAdapter.setOnItemClickListener(this);
        }
        return mAdapter;
    }

    @Override
    public void refreshData() {
        setRefreshing(false);
    }

    @Override
    public void loadMoreData(int currentPage) {

    }

    @Override
    public void refreshData(List<GoodsItem> list) {
        if (ListUtils.isEmpty(list)) {
            mTvNoContent.setVisibility(View.VISIBLE);
        } else {
            mTvNoContent.setVisibility(View.GONE);
        }
        mAdapter.refreshData(list);
    }

    @Override
    public void loadMoreData(List<GoodsItem> list) {

    }

    @Override
    public void getDataFailed(String errorMsg) {

    }

    @Override
    public void onItemClick(View view, int position) {
        GoodsDetailActivity.startActivity(getActivity(), mAdapter.getItemObject(position).getGoods_id());
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void setPresenter(GoodsSearchContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @OnClick(R.id.fab_speak)
    public void onClick() {

        mIat.startListening(mRecognizerListener);
    }

}
